package com.zbec.mdrs.web;

import com.zbec.framework.core.vo.JqgridResponse;
import com.zbec.framework.core.vo.PageInfo;
import com.zbec.framework.security.service.SecurityService;
import com.zbec.mdrs.constants.Constants;
import com.zbec.mdrs.entity.guarantee.Guarantee;
import com.zbec.mdrs.entity.history.History;
import com.zbec.mdrs.entity.report.ReportConfig;
import com.zbec.mdrs.service.*;
import com.zbec.mdrs.util.BusinessException;
import com.zbec.mdrs.util.ResourceUtils;
import com.zbec.mdrs.vo.*;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by fxl on 2015/10/18.
 */
@Controller
@RequestMapping(value = "/mbt")
public class MbtController extends  BaseController {


    @Autowired
    private HistoryService historyService;

    @Autowired
    private LoanService loanService;

    @Autowired
    private DiscountService discountService;

    @Autowired
    private EntrustedLoanService entrustedLoanService;

    @Autowired
    private DraftsService draftsService;

    @Autowired
    private GuaranteeService guaranteeService;

    @Autowired
    private MbtService mbtService;

    @Autowired
    private SecurityService securityService;

    @Autowired
    private LogsService logsService;

    @Autowired
    private  ReportConfigService reportConfigService;

    @RequestMapping(value = "/toHistory")
    public String toHistory(HttpServletRequest request) {
            return "mbt/mbrHistory";
    }

    @RequestMapping(value = "/toViewDetail")
    public ModelAndView toViewDetail(MbtVo vo,HttpServletRequest request) {
        ModelAndView view=new ModelAndView();
        view.addObject("historyId",vo.getHistoryId());
        String type=vo.getBusinessType();
        switch (type){
            case Constants.BUSINESS_TYPE_LOAN :
                view.setViewName("mbt/history_loan");
                break;
            case Constants.BUSINESS_TYPE_DISCOUNT :
                view.setViewName("mbt/history_discount");
                break;
            case Constants.BUSINESS_TYPE_DRAFTS :
                view.setViewName("mbt/history_drafts");
                break;
            case Constants.BUSINESS_TYPE_ENTRUSTED_LOAN :
                view.setViewName("mbt/history_entrusted_loan");
                break;
            case Constants.BUSINESS_TYPE_GUARANTEE :
                view.setViewName("mbt/history_guarantee");
                break;
            default:
                view.setViewName("mbt/history_loan");
                break;

        }

        return view;
    }

    @RequestMapping(value = "/loanView")
    @ResponseBody
    public JqgridResponse<LoanVo> findLoanByHistroy(MbtVo vo,PageInfo pageInfo,HttpServletRequest request) {

        JqgridResponse<LoanVo> loanVoJqgridResponse=loanService.findLoanByHistoryId(vo.getHistoryId(), pageInfo);
        return loanVoJqgridResponse;
    }

    @RequestMapping(value = "/discountView")
    @ResponseBody
    public JqgridResponse<DiscountVo> findDiscountByHistroy(MbtVo vo,PageInfo pageInfo,HttpServletRequest request) {

        JqgridResponse<DiscountVo> discountVoJqgridResponse=discountService.findDiscountByHistroy(vo.getHistoryId(), pageInfo);
        return discountVoJqgridResponse;
    }

    @RequestMapping(value = "/draftsView")
    @ResponseBody
    public JqgridResponse<DraftsVo> findDraftsByHistroy(MbtVo vo,PageInfo pageInfo,HttpServletRequest request) {

        JqgridResponse<DraftsVo> draftsVoJqgridResponse=draftsService.findDraftsByHistroy(vo.getHistoryId(), pageInfo);
        return draftsVoJqgridResponse;
    }

    @RequestMapping(value = "/entrustedLoanView")
    @ResponseBody
    public JqgridResponse<EntrustedLoanVo> findEntrustedLoanByHistroy(MbtVo vo,PageInfo pageInfo,HttpServletRequest request) {

        JqgridResponse<EntrustedLoanVo>  entrustedLoanVoJqgridResponse=entrustedLoanService.findEntrustedLoanByHistroy(vo.getHistoryId(), pageInfo);
        return entrustedLoanVoJqgridResponse;
    }

    @RequestMapping(value = "/guaranteeView")
    @ResponseBody
    public JqgridResponse<GuaranteeVo> findGuaranteeByHistroy(MbtVo vo,PageInfo pageInfo,HttpServletRequest request) {

        JqgridResponse<GuaranteeVo>  guaranteeVoJqgridResponse=guaranteeService.findGuaranteeByHistroy(vo.getHistoryId(), pageInfo);
        return guaranteeVoJqgridResponse;
    }



    @RequestMapping(value = "/mbtHistory")
    @ResponseBody
    public JqgridResponse<HistoryVo> findAllHistory(PageInfo pageInfo,HttpServletRequest request) {

        JqgridResponse<HistoryVo> historyJqgridResponse=historyService.findAllHistory(pageInfo);
        return historyJqgridResponse;
    }

    @RequestMapping(value = "/toExport")
    public String toExport(HttpServletRequest request) {
        if(this.isUserReseted(securityService.getCurrentUserVO())){
            return "system/editPassword";
        }else{
            ReportConfig config=reportConfigService.findReportConfig();
            if (Constants.SOURCE_MBT.equals(config.getImportType())){
                return "mbt/historyInput";
            }else{
                return "mbt/mbt_import";
            }

        }
    }

    @RequestMapping(value = "/mbtExport")
    @ResponseBody
    public String export(@ModelAttribute("mbtVo") MbtVo mbtVo, HttpServletRequest request) {
        JSONObject object=new JSONObject();
        String year=mbtVo.getBusinessDate().substring(0,4);
        String month=mbtVo.getBusinessDate().substring(5, 7);
        String[] bizChecked=mbtVo.getBusinessType().split(",");
        boolean isDistrice=false;
        if(mbtVo.getRestraintDistrict()!=null && mbtVo.getRestraintDistrict().equals("1"))
        {
            isDistrice=true;
        }

        String ip=this.getIPAddress(request);
        String message= mbtService.exportMBTDataByMonth(year,month,bizChecked,isDistrice,ip);

        object.put("result","true");
        object.put("message", message);
       return object.toJSONString();
    }

    @RequestMapping(value = "/mbtImport")
    @ResponseBody
    public String mbtImport(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "importfile") MultipartFile[] importfile,
                            @RequestParam("tempType") String tempType) throws Exception{
        JSONObject object=new JSONObject();
        MultipartFile file=importfile[0];
        String importFileFileName = file.getOriginalFilename();
        String userIp=getIPAddress(request);
        if (importFileFileName != null) {
            if (!importFileFileName.endsWith(".xls")&&!importFileFileName.endsWith(".xlsx")&&!importFileFileName.endsWith(".txt")) {
                object.put("result", "false");
                object.put("message", ResourceUtils.getLocaleString("logs.mbt.message.importformatfailure"));
            }else{
                String message="true";
                String error="";
                try{
                    message = mbtService.mbtImport(file,userIp,tempType);
                }catch (BusinessException be){
                    error= be.getMessage();
                    message="false";
                }
                catch (Exception e){
                    e.printStackTrace();
                    message="false";
                }
                if (!message.equals("false")) {
                    object.put("result", "true");
                    object.put("message", ResourceUtils.getLocaleString("logs.mbt.message.importsuccess")+"==="+message);
                } else {
                    object.put("result", "false");
                    object.put("message", ResourceUtils.getLocaleString("logs.mbt.message.importfailure")+"==="+error);
                    logsService.handleBuzLogData(userIp,"logs.mbt.importUpdate","logs.mbt.operation.importUpdate",false,ResourceUtils.getLocaleString("logs.mbt.message.importfailure"));
                }
            }
        }
        return object.toJSONString();
    }




}
